package com.meitianhui.convenitenbuy.module.order.presenter;

import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseResponse;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.home.model.bean.OneOrder;
import com.meitianhui.convenitenbuy.module.order.contract.OrderPayContract;
import com.meitianhui.convenitenbuy.module.order.http.OrderApiDataSource;
import com.meitianhui.convenitenbuy.module.order.model.bean.UsableCash;
import com.meitianhui.convenitenbuy.module.order.ui.activity.OrderPayActivity;
import com.meitianhui.convenitenbuy.module.wallet.http.WalletApiDataSource;
import com.meitianhui.convenitenbuy.module.wallet.model.AlipayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.RechargeBackInfoBean;
import com.meitianhui.convenitenbuy.util.DateUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class OrderPayPresenter implements OrderPayContract.Presenter {

    private OrderPayActivity mContext;
    private OrderPayContract.View view;
    private final IWXAPI wxApi;

    public OrderPayPresenter(OrderPayContract.View view, OrderPayActivity context) {
        this.view = view;
        this.mContext = context;
        wxApi = WXAPIFactory.createWXAPI(context, Constants.WX_APP_ID, true);
    }

    @Override
    public void getUsableCash() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", InfoProvider.getUserToken(mContext).getMember_id());
        map.put("member_type_key", "consumer");
        String json = new Gson().toJson(map);

        OrderApiDataSource.getInstance()
                .getUsableCash(InfoProvider.getUserToken(mContext).getUser_token(),
                        "finance.usableCashBalanceFind", json)
                .subscribe(new ResponseObserver<BaseResponse<UsableCash>>(mContext) {
                    @Override
                    public void onSuccess(BaseResponse<UsableCash> response) {
                        view.getUsableCashSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        view.onFail(code, msg);
                    }
                });
    }

    @Override
    public void orderPay(String fromPage, int payWay, String num, String itemId,
                         String feedBack, String price, String deliveryAddress,
                         String contactPerson, String contactTel, OneOrder oneOrder) {
        HashMap params = new HashMap<>();
        HashMap<String, String> map = new HashMap<>();
        params.put("data_source", Constants.CUSTOM_APP);
        if (payWay == 0) {
            params.put("payment_way_key", Constants.PAYMENT_WAY_05);
        } else if (payWay == 1) {
            params.put("payment_way_key", Constants.ALIPAY_APY);
        } else if (payWay == 2) {
            params.put("payment_way_key", Constants.WECHAT_APY);
        }
        if (fromPage.equals(Constants.TYPE_COUPON)) {//优惠券购买
            params.put("detail", "优惠券");
        } else if (fromPage.equals(Constants.TYPE_ONE_BUY)) {
            params.put("detail", "一元购");//一元购
        }
        params.put("amount", price.replace("¥", ""));
        params.put("buyer_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
        params.put("seller_id", Constants.SELLER_ID);
        if (fromPage.equals(Constants.TYPE_COUPON)) {//优惠券购买
            params.put("detail", "优惠券");
            params.put("order_type_key", "DDLX_02");//表示C端
        } else if (fromPage.equals(Constants.TYPE_ONE_BUY)) {
            params.put("detail", "一元购");//一元购
            params.put("order_type_key", "DDLX_03");//表示一元购
        } else if (fromPage.equals(Constants.TYPE_GOLD_BUY)) {
            params.put("detail", "名品汇");//金币兑换
            params.put("order_type_key", "DDLX_05");//表示金币兑
            params.put("buyer_id", Constants.BUYER_ID);  //买方
            params.put("seller_id", Constants.SELLER_ID);  //卖方
        }
        params.put("transaction_date", DateUtil.getyyyyMMddHHmmss());//表示C端
        if (fromPage.equals(Constants.TYPE_COUPON)) {
            map.put("item_id", itemId);
            map.put("member_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
            map.put("member_type_key", "consumer");
            map.put("num", num);
        } else if (fromPage.equals(Constants.TYPE_ONE_BUY)) {
            if (oneOrder != null) {
                map.put("consumer_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
                map.put("stores_id", oneOrder.stores_id);
                map.put("activity_id", oneOrder.activity_id);
                map.put("price", oneOrder.price);
                map.put("qty", oneOrder.qty);
                map.put("total_fee", oneOrder.total_fee);
            }
        } else if (fromPage.equals(Constants.TYPE_GOLD_BUY)) {
            if (oneOrder != null) {
                map.put("data_source", Constants.CUSTOM_APP);
                map.put("member_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
                map.put("member_type_key", "consumer");
                map.put("member_info", InfoProvider.getUserToken(App.getInstance()).getMobile());
                map.put("desc1", oneOrder.title);
                map.put("item_num", "1");
                map.put("cash_amount", oneOrder.discount_price);
                map.put("gold_amount", oneOrder.gold);
                map.put("remark", feedBack);
                if (payWay == 0) {
                    map.put("payment_way_key", Constants.PAYMENT_WAY_05);
                } else if (payWay == 1) {
                    map.put("payment_way_key", Constants.ALIPAY_APY);
                } else if (payWay == 2) {
                    map.put("payment_way_key", Constants.WECHAT_APY);
                }
                map.put("delivery_address", deliveryAddress);   //地址
                map.put("contact_person", contactPerson);
                map.put("contact_tel", contactTel);
                Map<String, String> map1 = new HashMap<>();
                map1.put("goods_id", oneOrder.goods_id);
                map1.put("goods_code", oneOrder.goods_code);
                map1.put("goods_title", oneOrder.title);
                map1.put("goods_pic_info", oneOrder.pic_info);
                map1.put("qty", "1");
                map1.put("specification", oneOrder.specification);
                map1.put("goods_unit", oneOrder.goods_unit);
                map1.put("retail_price", oneOrder.market_price);
                map1.put("discount_price", oneOrder.discount_price);
                map1.put("cash_paid", oneOrder.discount_price);
                map1.put("gold_paid", oneOrder.gold);
                map.put("order_item_list", "[" + new Gson().toJson(map1) + "]");
            }
        }
        params.put("out_trade_body", new Gson().toJson(map));
        String paramJson = new Gson().toJson(params);

        WalletApiDataSource.getInstance()
                .getRechargeOrder(InfoProvider.getUserToken(App.getInstance()).getUser_token(),
                        "finance.orderPay", paramJson)
                .subscribe(new ResponseObserver<BaseResponse<RechargeBackInfoBean>>(mContext) {
                    @Override
                    public void onSuccess(BaseResponse<RechargeBackInfoBean> response) {
                        RechargeBackInfoBean result = response.data;
                        if (payWay == 1) {
                            wakeUpAliPay(result);
                        } else if (payWay == 2) {
                            wakeUpWeChat(result);
                        } else {
                            view.walletPaySuccess();
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                    }
                });
    }

    private void wakeUpAliPay(RechargeBackInfoBean bean) {
        String orderInfo = bean.getAlipay_params();
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                PayTask alipay = new PayTask(mContext);
                String result = alipay.pay(orderInfo, true);
                emitter.onNext(result);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                AlipayResultBean payResult = new AlipayResultBean(s);
                String resultInfo = payResult.getResult();
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                if (TextUtils.equals(resultStatus, "9000")) {
                    TipUtils.showToast(mContext, mContext.getString(R.string.wallet_change_recharge_success), 1);
                    RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_SUCCESS));
                    RxBus.get().post(new EventBean(Constants.EVENT_TYPE_REFRESH));
                } else {
                    // 判断resultStatus 为非“9000”则代表可能支付失败
                    // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，
                    // 最终交易是否成功以服务端异步通知为准（小概率状态）
                    if (TextUtils.equals(resultStatus, "8000")) {
                        TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_confirming), 3);
                    } else {
                        // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_fail));
                    }
                }
            }
        });
    }

    public void wakeUpWeChat(RechargeBackInfoBean result) {
        boolean ifInstall = SystemUtils.isWXAppInstalledAndSupported(mContext, result.getAppid());
        if (!ifInstall) {
            TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_order_wechat_uninstall));
            return;
        }
        PayReq req = new PayReq();
        req.appId = result.getAppid();
        req.nonceStr = result.getNoncestr();
        req.packageValue = result.getPackageValue();
        req.partnerId = result.getPartnerid();
        req.prepayId = result.getPrepayid();
        req.timeStamp = result.getTimestamp();
        req.sign = result.getSign();
        wxApi.registerApp(result.getAppid());
        wxApi.sendReq(req);
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

}
